/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controlador;

import model.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;

/**
 *
 * @author sheked
 */
public class ServletControler extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        HttpSession sessio = request.getSession(true);
        if (sessio.isNew()) {
            sessio.setAttribute("idCarret", null);
            sessio.setAttribute("id", null);
            sessio.setAttribute("nom", null);
            sessio.setAttribute("cognoms", null);
            sessio.setAttribute("isAdmin", Boolean.FALSE);
            sessio.setAttribute("isLogged", Boolean.FALSE);
            sessio.setAttribute("numProdPagina",Integer.valueOf(9));
        }

        RequestDispatcher reqDispatcher;
        try {
            if (sessio.getAttribute("idCarret") == null) {
                sessio.setAttribute("totalCarret", Float.valueOf((float)0.0));
                sessio.setAttribute("itemsCarret", Integer.valueOf(0));
            } else {
                CarretDB carret = new CarretDB();
                Float pt = Float.valueOf(carret.preuTotal((Integer)sessio.getAttribute("idCarret")));
                Integer items = Integer.valueOf(carret.itemsTotal((Integer)sessio.getAttribute("idCarret")));
                DecimalFormat formatter = new DecimalFormat("#####0.00");
                if (pt >= 0 && items >= 0) {
                    sessio.setAttribute("totalCarret", formatter.format(pt));
                    sessio.setAttribute("itemsCarret", items);
                    sessio.setAttribute("llistatCarret", carret.llistat((Integer)sessio.getAttribute("idCarret")));
                } else {
                    response.sendError(4);
                }
            }
            CategoriaDB categoriaDb = new CategoriaDB();
            int i = 0;
            int j = 0;
            ArrayList<String[]> cats = new ArrayList<String[]>();
            ArrayList<String[]> subCats = null;
            Iterator<Map<String, Object>> itCat = categoriaDb.consultaCategories().iterator();
            Iterator<Map<String, Object>> itSubCat = null;
            Map<String, Object> cat = null;
            Map<String, Object> subcat = null;
            while (itCat.hasNext()) {
                cat = itCat.next();
                String idcat = (String) cat.get("id_cat");
                String nom = (String) cat.get("nom_cat");

                String[] acat = new String[2];
                acat[0] = idcat;
                acat[1] = nom;
                cats.add(i, acat);
                
                itSubCat = categoriaDb.consultaSubcategories(idcat).iterator();
                j = 0;
                subCats = new ArrayList<String[]>();
                while (itSubCat.hasNext()) {
                    subcat = itSubCat.next();
                    String idsubcat = (String) subcat.get("id_subcat");
                    String nomSub = (String) subcat.get("nom_subcat");

                    String[] asubcat = new String[2];
                    asubcat[0] = idsubcat;
                    asubcat[1] = nomSub;
                    subCats.add(j, asubcat);
                    j++;
                }
                request.setAttribute(nom, subCats);
                i++;
            }
            request.setAttribute("categories", cats);

            reqDispatcher = getServletContext().getRequestDispatcher("/estructura.jsp");
            reqDispatcher.forward(request,response);
        } catch (Exception ex) {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Solidaria de Servei</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<div>No s'ha pogut connectar correctament amb la base de dades, intentiu mes tard</div>");
            out.println("<pre>");
            ex.printStackTrace(out);
            out.println("</pre>");
            out.println("</body>");
            out.println("</html>");
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
